import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';

import 'package:riki_base_flutter/riki_base_flutter.dart';
import 'package:riki_base_flutter/router/fluro_navigator.dart';
import 'package:riki_login/pages/staff/widgets/login_privacy_widget.dart';
import 'package:riki_login/res/header.dart';
import 'user_login_code_viewmodel.dart';
import 'package:wangyi_yidun_flutter_plugin/wangyi_yidun_flutter_plugin.dart';
///作者：范玉辉
///创建时间：2020/12/15
///说明：APP2.0验证码登录

class UserLoginCodePage extends StatefulWidget {
  // final LoginArg loginArg;

  UserLoginCodePage();

  @override
  _UserLoginCodePageState createState() => _UserLoginCodePageState();
}

class _UserLoginCodePageState extends BaseScaffoldState<UserLoginCodePage> {
  var eventChannel = const EventChannel("yd_captcha_flutter_event_channel");
  late UserLoginCodeViewModel viewModel;

  //手机号输入框控制器，此控制器可以监听手机号输入框操作
  TextEditingController _userPhoneController = TextEditingController();
  TextEditingController _userCodeController = TextEditingController();

  List<BoxShadow> cardShadow = [
    BoxShadow(
        offset: Offset(0, 6),
        color: RikiLoginColors.cardShadowColor,
        blurRadius: 14.w, //阴影模糊程度
        spreadRadius: -6.w //阴影扩散程度
        ),
  ];

  //表单状态
  GlobalKey _formKey = GlobalKey();

  bool isAgreement = RikiLoginGlobal.isUserAgreeAgreement();

  // late StreamSubscription<LoginSuccessEvent> _eventStream;

  // 验证手机号
  String validateUserName(value) {
    // 正则匹配手机号
    RegExp exp = RegExp(r'^(13|14|15|16|17|18|19)\d{9}$');
    if (!exp.hasMatch(value)) {
      return '手机号格式错误!';
    }
    return '';
  }

  @override
  bool isPageObserver() => true;

  @override
  void didPopNext() {
    super.didPopNext();
    setState(() {
      this.isAgreement = RikiLoginGlobal.isUserAgreeAgreement();
    });
  }

  @override
  void initState() {
    // 网易滑块回调
    eventChannel.receiveBroadcastStream().listen(_onData, onError: _onError);

    //监听手机号框的输入改变
    _userPhoneController.addListener(() {
      // 监听文本框输入变化，当有内容的时候，显示尾部清除按钮，否则不显示
      if (_userPhoneController.text.length > 0) {
        viewModel.setShowClear(true);
      } else {
        viewModel.setShowClear(false);
      }
    });
    super.initState();
  }

  @override
  void dispose() {
    // _eventStream.cancel();
    _userPhoneController.dispose();
    _userCodeController.dispose();
    super.dispose();
  }

  /// 网易验证成功
  void _onData(response) {
    print(response);
    var validate = (response as Map)['validate'];
    if (validate != null && !validate.isEmpty) {
      print(validate);
      //发送验证码
      getLoginCode(validate);
    }
  }

  /// 网易验证出现错误
  void _onError(Object error) {
    ToastUtil.showNegativeToast('加载验证码出现错误');
  }

  @override
  bool resizeToAvoidBottomInset() => false;

  @override
  Widget buildAppBar(BuildContext context) {
    return RikiAppBar(
      onBackPressed: () => NavigatorUtils.goBack(context),
    );
  }

  @override
  Widget buildBody(BuildContext context) {
    return ProviderWidget<UserLoginCodeViewModel>(
      builder: (context, model, child) {
        return _buildBodyWidget();
      },
      model: UserLoginCodeViewModel(),
      onModelReady: (model) {
        viewModel = model;
        viewModel.initApi(context);
      },
      pageStatusFactory: DefaultPageStatusFactory(),
    );
  }

  Widget _buildBodyWidget() {
    return GestureDetector(
      onTap: () => FocusScope.of(context).requestFocus(FocusNode()),
      child: Container(
        width: 375.w,
        color: RikiLoginColors.app_white,
        child: Stack(
          alignment: Alignment.center,
          children: [
            // 账号和验证码内容
            containWidget(),
            // 底部功能区域
            bottomWidget(),
          ],
        ),
      ),
    );
  }

  /// 账号和验证码内容
  Widget containWidget() {
    return Container(
      margin: EdgeInsets.only(top: 20.w, left: 37.5.w, right: 37.5.w),
      child: Form(
        key: _formKey,
        child: Column(
          children: [
            Row(
              children: [
                Text(
                  "验证码登录",
                  style: TextStyle(
                    fontSize: 30.sp,
                    fontWeight: FontWeight.bold,
                    color: RikiLoginColors.text_333333,
                  ),
                ),
              ],
            ),
            Container(
              padding: EdgeInsets.only(top: 50.w),
              child: Selector<UserLoginCodeViewModel, bool>(
                selector: (ctx, model) {
                  return model.isShowClear;
                },
                builder: (ctx, showClear, child) {
                  return TextFormField(
                    controller: _userPhoneController,
                    autofocus: true,
                    //光标颜色
                    cursorColor: RikiLoginColors.app_main,
                    cursorWidth: 2,
                    keyboardType: TextInputType.number,
                    //设置键盘类型,
                    decoration: InputDecoration(
                      border: InputBorder.none,
                      hintText: "请输入手机号",
                      hintStyle: TextStyle(
                        color: RikiLoginColors.text_999999,
                      ),
                      focusedBorder: UnderlineInputBorder(
                        borderSide: BorderSide(
                          color: RikiLoginColors.app_transparent, //输入框底边线
                        ),
                      ),
                      //尾部添加清除按钮
                      suffixIcon: (showClear)
                          ? GestureDetector(
                              onTap: () {
                                // 清空输入框内容
                                _userPhoneController.clear();
                                viewModel.setUserPhone('');
                              },
                              child: Container(
                                padding: EdgeInsets.only(left: 20.w),
                                child: ImageUtil.loadAssetImage(R.libAssetsIcLoginInputClear, width: 24.w, height: 24.w,package: RikiLogin.PACKAGE),
                              ),
                            )
                          : Empty.ui,
                    ),
                    inputFormatters: <TextInputFormatter>[
                      FilteringTextInputFormatter.digitsOnly, //只输入数字
                      LengthLimitingTextInputFormatter(11) //限制长度
                    ],
                    //验证手机号
                    validator: validateUserName,
                    //保存数据
                    onChanged: (String value) {
                      viewModel.setUserPhone(value);
                    },
                  );
                },
              ),
            ),
            // MDivide(color: Color.fromRGBO(153, 153, 153, 0.3)),
            Row(
              children: [
                Expanded(
                  child: Container(
                    margin: EdgeInsets.only(top: 30.w),
                    child: TextFormField(
                      controller: _userCodeController,
                      //光标颜色
                      cursorColor: RikiLoginColors.app_main,
                      cursorWidth: 2,
                      keyboardType: TextInputType.number,
                      //设置键盘类型
                      decoration: InputDecoration(
                        hintText: "请输入验证码",
                        hintStyle: TextStyle(
                          color: RikiLoginColors.text_999999,
                        ),
                        border: InputBorder.none,
                        focusedBorder: UnderlineInputBorder(
                          borderSide: BorderSide(
                            color: RikiLoginColors.app_white, //输入框底边线
                          ),
                        ),
                      ),

                      inputFormatters: <TextInputFormatter>[
                        FilteringTextInputFormatter.digitsOnly, //只输入数字
                        LengthLimitingTextInputFormatter(6) //限制长度
                      ],
                      //保存数据
                      onChanged: (String value) {
                        viewModel.setUserCode(value);
                      },
                    ),
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(top: 30.w),
                  child: Selector<UserLoginCodeViewModel, String>(builder: (BuildContext context, sendCode, Widget? child) {
                    return sendCode == '获取验证码'
                        ? Selector<UserLoginCodeViewModel, int>(
                            selector: (ctx, model) {
                              return model.phoneLen;
                            },
                            builder: (ctx, len, child) {
                              return GradientBgButton(
                                onTap: () {
                                  showCaptcha();
                                },
                                enabled: len == 11,
                                width: 75.w,
                                height: 25.w,
                                title: sendCode,
                                fontSize: 11.sp,
                              );
                            },
                          )
                        : GestureDetector(
                            onTap: () {
                              if (sendCode == '重发') {
                                showCaptcha();
                              }
                            },
                            child: Container(
                              alignment: Alignment.centerRight,
                              width: 75.w,
                              height: 25.w,
                              child: Text(
                                sendCode,
                                style: sendCode == '重发' ? _textMediumStyle : _textRegularStyle,
                              ),
                            ),
                          );
                  }, selector: (BuildContext context, UserLoginCodeViewModel counterProvider) {
                    return counterProvider.sendCode;
                  }),
                ),
              ],
            ),
            // MDivide(color: Color.fromRGBO(153, 153, 153, 0.3)),
            45.vGap,
            Selector<UserLoginCodeViewModel, bool>(
              selector: (ctx, model) {
                return model.loginBtnEnable;
              },
              builder: (ctx, enable, child) {
                return Container(
                  decoration: BoxDecoration(
                    boxShadow: enable ? cardShadow : null,
                  ),
                  child: GradientBgButton(
                    onTap: () {
                      loginClick();
                    },
                    enabled: enable,
                    width: 300.w,
                    height: 44.w,
                    title: "登录/注册",
                    fontSize: 16.sp,
                  ),
                );
              },
            ),
            13.vGap,
            LoginPrivacyWidget(this.isAgreement, (isAgreement) {
              if (mounted)
                setState(() {
                  this.isAgreement = isAgreement;
                });
            }),
          ],
        ),
      ),
    );
  }
  //
  // Widget bottomWidget() {
  //   return Positioned(
  //     bottom: 10.w + MediaQuery.of(context).padding.bottom,
  //     child: LoginBottomWidget(
  //       clickOnTap: () => NavigatorUtils.push(context, AppRouter.loginPassword).then((value) {
  //         if (value != null) {
  //           setState(() {
  //             this.isAgreement = value;
  //           });
  //         }
  //       }),
  //       title: '密码登录',
  //       image: R.libAssetsIcLoginCode,
  //     ),
  //   );
  // }


  Widget bottomWidget() {
    return Positioned(
      bottom: MediaQuery.of(context).padding.bottom,
      right: 0,
      left: 0,
      child: Column(
        children: [
          GestureDetector(
            onTap: () => NavigatorUtils.push(context, RikiLoginRouter.staffLoginPassword).then((value) {
              if (value != null) {
                setState(() {
                  this.isAgreement = value;
                });
              }
            }),
            child: Center(
              child: Column(
                children: <Widget>[
                  ImageUtil.loadAssetImage(R.libAssetsIcLoginCode, width: 40.w, height: 40.w,package: RikiLogin.PACKAGE),
                  6.vGap,
                  Text(
                    '密码登录',
                    style: TextStyle(fontSize: 12.sp, color: RikiLoginColors.text_333333),
                  )
                ],
              ),
            ),
          ),
          25.vGap,
        ],
      ),
    );
  }


  // 登录
  void loginClick() async {
    if (viewModel.userPhone.length != 11 || viewModel.userCode.length == 0) {
      return;
    }
    if (!this.isAgreement) {
      ToastUtil.show("请勾选服务协议!");
      return;
    }
    // 手机号是否填写
    if (viewModel.userPhone.length == 0) {
      print(viewModel.userPhone);
      ToastUtil.show('请输入手机号');
      return;
    }
    // 手机号是否填写
    if (viewModel.userPhone.length < 11 && viewModel.userPhone.length > 0) {
      print(viewModel.userPhone);
      ToastUtil.show('手机号错误，请重新输入');
      return;
    }

    showLoading(afterDismiss: () {
      // if (!Provider.of<UserViewModel>(context, listen: false).isLogout) {
      // LoginEntity? userInfo = Global.getLocalUserAccount();
      // if (userInfo == null) {
      //   // RikiApplication.eventBus.fire(TokenInvalidEvent());
      // } else {
      //   RikiBase.setAccessToken(userInfo.accessToken ?? '');
      //
      //   Application.instance.loginIm(userInfo);
      //   RikiApplication.eventBus.fire(LoginSuccessEvent());
      //   NavigatorUtils.popUntil(context, AppRouter.root);

      //   viewModel.userLoginRecord();
      //   ToastUtil.showPositiveToast('登录成功');
      // }
      // }
      NavigatorUtils.popUntil(context, '');
      RikiLogin.instance.onLoginSuccessCallback(context);
      ToastUtil.showPositiveToast('登录成功');
    });

    //! 登录成功 埋点相关
    viewModel.checkCode().whenComplete(() => {hideLoading()});
  }

  Future<void> showCaptcha() async {
    // 手机号和验证码是否填写
    // 手机号是否填写
    if (viewModel.userPhone.length == 0) {
      print(viewModel.userPhone);
      ToastUtil.show('请输入手机号');
      return;
    }
    // 手机号是否填写
    if (viewModel.userPhone.length < 11 && viewModel.userPhone.length > 0) {
      print(viewModel.userPhone);
      ToastUtil.show('手机号错误，请重新输入');
      return;
    }
    if (viewModel.sendCode != '获取验证码' && viewModel.sendCode != '重发') {
      return;
    }
    //协议是否开着
    if (!this.isAgreement) {
      ToastUtil.show("请勾选服务协议!");
      return;
    }
    // 关闭键盘
    FocusScope.of(context).requestFocus(FocusNode());
    WangyiYidunFlutterPlugin.setup(appKey: RikiLogin.instance.netEasyAppKey);
  }

  // 获取验证码
  void getLoginCode(String neCaptchaValidate) async {
    // //! 点击获取验证码的埋点
    // RikiEventTracker()
    //     .trackCustomEvent(GioUserEventSymbol.clickMessage, variable: {
    //   GioUserParamKey.loginSource_var: "${widget.loginArg.gioStr}",
    // });

    // 发送验证码
    showLoading();
    viewModel.sendSmsCodeFun(neCaptchaValidate).whenComplete(() => hideLoading());
  }

  TextStyle _textMediumStyle = TextStyle(color: RikiLoginColors.app_main, fontSize: 11.sp, fontWeight: FontWeightExt.medium);
  TextStyle _textRegularStyle = TextStyle(color: RikiLoginColors.text_333333, fontSize: 11.sp);
}
